import request from './request'

// 基础请求方法
export const get = (url, params = {}) => {
	return request({
		url,
		method: 'get',
		params,
	})
}

export const post = (url, data = {}) => {
	return request({
		url,
		method: 'post',
		data,
	})
}

export const put = (url, data = {}) => {
	return request({
		url,
		method: 'put',
		data,
	})
}

export const del = (url, params = {}) => {
	return request({
		url,
		method: 'delete',
		params,
	})
}

// 获取字典数据
export const getDic = async (type) => {
	const dicKey = `dicKey:${type}`
	const cached = localStorage.getItem(dicKey)

	if (cached) {
		try {
			const parsedCache = JSON.parse(cached)
			const now = Date.now()
			// 缓存24小时
			if (now - parsedCache.timestamp < 24 * 60 * 60 * 1000) {
				return parsedCache.data
			}
		} catch (e) {
			localStorage.removeItem(dicKey)
		}
	}

	try {
		const res = await get(`/api/form/dict/getType?dictType=${type}`)
		if (res.code === '0') {
			// 缓存字典数据
			localStorage.setItem(
				dicKey,
				JSON.stringify({
					data: res.data,
					timestamp: Date.now(),
				})
			)
			return res.data
		} else {
			throw new Error(`获取字典[${type}]失败`)
		}
	} catch (error) {
		console.error('获取字典失败:', error)
		throw error
	}
}

// 获取位置信息（H5版本）
export const getLocation = () => {
	return new Promise((resolve, reject) => {
		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(
				(position) => {
					const latitude = position.coords.latitude
					const longitude = position.coords.longitude
					resolve({
						jd: longitude,
						wd: latitude,
						longitude: longitude,
						latitude: latitude,
					})
				},
				(error) => {
					console.error('获取位置失败:', error)
					reject(error)
				}
			)
		} else {
			reject(new Error('浏览器不支持地理位置'))
		}
	})
}

// 用户登录 - 参考小程序逻辑
export const loginByOpenId = (openId) => {
	return post('/api/user/login', { openId })
}

// 获取污染源信息
export const locationPollution = () => {
	return post('/api/bizPollutionSourceInfo/getByBind')
}

// 文件上传URL
export const uploadFileUrl = `${import.meta.env.VITE_APP_BASE_API}/api/upload/updateFile`

export default {
	get,
	post,
	put,
	del,
	getDic,
	getLocation,
	loginByOpenId,
	locationPollution,
	uploadFileUrl,
}
